﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model;
using DeviceMaintainGIS.Model.Field;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using static DeviceMaintainGIS.Model.Field.FieldRequest;

namespace DeviceMaintainGIS.BLL.Field
{
    /// <summary>
    /// 现场服务操作
    /// </summary>
    public class FieldService
    {
        /// <summary>
        /// 根据条件查询现场服务信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnListVM<FieldResponse> GetFieldList(FieldSelectRequest request)
        {
            ReturnListVM<FieldResponse> list = new ReturnListVM<FieldResponse>();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from k in Entities.RepairRelation_Tab//.Where(i => i.State == 0 && i.NextOperatorID == request.NextOperatorID && i.Operator == 3)
                           join f in Entities.Field_Tab on k.RelationGuid equals f.Guid
                           into tmpField
                           let a = tmpField.FirstOrDefault()
                           join ur in Entities.tbUser on k.OperatorID equals ur.ID
                           into tmptbUser
                           from tbUser in tmptbUser.DefaultIfEmpty()
                           select new FieldResponse
                           {
                               RepairId = a.RepairId,
                               Describe = a.Describe,
                               Guid = a.Guid,
                               AddTime = a.AddTime,
                               RepairOrChange = a.RepairOrChange,
                               OperatorID = k.OperatorID,
                               Step = k.Step,
                               State = k.State,
                               OperatorName = tbUser == null ? "" : tbUser.RealName,
                           };
                //报修编号查询条件
                if (!string.IsNullOrEmpty(request.RepairId))
                {
                    linq = linq.Where(i => i.RepairId == request.RepairId);
                }
                //操作人查询条件
                if (request.OperatorID != 0)
                {
                    linq = linq.Where(i => i.OperatorID == request.OperatorID);
                }
                //步骤查询条件
                if (request.Step != 0)
                {
                    linq = linq.Where(i => i.Step == request.Step);
                }
                //现场服务ID查询条件
                if (!string.IsNullOrEmpty(request.FieldID))
                {
                    linq = linq.Where(i => i.Guid == request.FieldID);
                }
                list.TotalCount = linq.Count();
                List<FieldResponse> FieldResponseList = linq.OrderByDescending(i => i.AddTime).Take(request.PagesSize * request.PageIndex).Skip(request.PagesSize * (request.PageIndex - 1)).ToList();
                //循环查询每个现场服务的图片集合
                foreach (FieldResponse fr in FieldResponseList)
                {
                    var Imglinq = from k in Entities.Image_Tab.Where(i => i.FGuid == fr.Guid)
                                  select new ImageTab
                                  {
                                      url = k.ImagePath,
                                      AddTime = k.AddTime,
                                      ModuleID = k.ModuleID
                                  };
                    fr.List = Imglinq.ToList();
                }
                list.List = FieldResponseList;
                list.PageIndex = request.PageIndex;
                list.PagesSize = request.PagesSize;
            }
            return list;
        }


        /// <summary>
        /// 添加或编辑现场服务信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        // POST: api/FieldHandle
        public ReturnMessageVM FieldOperation(FieldRequest request)
        {

            ReturnMessageVM rm = new ReturnMessageVM();
            if (string.IsNullOrEmpty(request.Guid))
            {
                rm = FieldAdd(request);
            }
            else
            {
                rm = FieldEdit(request);
            }
            return rm;
        }
        /// <summary>
        /// 添加现场服务信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM FieldAdd(FieldRequest request)
        {


            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            //现场服务表
            Field_Tab FieldTab = new Field_Tab();
            string newID = Guid.NewGuid().ToString();
            rm.Message = newID;
            FieldTab.Guid = newID;
            FieldTab.RepairId = request.RepairId;
            FieldTab.Describe = request.Describe;
            FieldTab.RepairOrChange = request.RepairOrChange;
            FieldTab.State = request.State;
            FieldTab.AddTime = System.DateTime.Now;



            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        Entities.Field_Tab.Add(FieldTab);
                        Entities.Entry<Field_Tab>(FieldTab).State = System.Data.Entity.EntityState.Added;

                        if (request.List != null && request.List.Count > 0)
                        {

                            foreach (FieldImage ImagePath in request.List)
                            {
                                Image_Tab it = new Image_Tab();
                                it.Guid= Guid.NewGuid().ToString();
                                it.FGuid = newID;
                                it.AddTime = ImagePath.AddTime;
                                it.ImagePath = ImagePath.url;
                                it.ModuleID = ImagePath.ModuleID;
                                Entities.Image_Tab.Add(it);
                                Entities.Entry<Image_Tab>(it).State = System.Data.Entity.EntityState.Added;
                            }
                        }

                        //查询上一步操作 更新其状态为已完成

                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step-1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }
                        //获取保修信息
                        Repair_Tab RepairTab = Entities.Repair_Tab.Where(i => i.RepairId == request.RepairId).FirstOrDefault();


                        //报修关系表
                        RepairRelation_Tab rrt = new RepairRelation_Tab();

                        rrt.RepairId = request.RepairId;
                        rrt.AddTime = System.DateTime.Now;
                        rrt.TableName = "Field_Tab";
                        rrt.RelationGuid = newID;
                        rrt.Step = request.Step;
                        rrt.OperatorID = request.OperatorID;
                        rrt.NextOperatorID = RepairTab.RMuserID;
                        //结束流程
                        if (request.State == -1)
                        {
                            rrt.State = 1;
                            rrt.Operator = -1;
                            //报修结束表
                            rrt.TableName = "RepairEnd_Tab";
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            rrt.State = request.State == 1 ? 0 : 2;
                            rrt.Operator =4;
                        }

                        Entities.RepairRelation_Tab.Add(rrt);
                        Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;



                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }
            return rm;
        }

        /// <summary>
        /// 编辑现场服务信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM FieldEdit(FieldRequest request)
        {


            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        List<Image_Tab> list = Entities.Image_Tab.Where(i => i.FGuid == request.Guid).ToList();
                        if (list.Count > 0)
                        {
                            foreach (Image_Tab it in list)
                            {
                                Entities.Image_Tab.Add(it);
                                Entities.Entry<Image_Tab>(it).State = System.Data.Entity.EntityState.Deleted;
                            }
                        }
                        Entities.SaveChanges();


                        //获取远程服务表信息
                        Field_Tab FieldTab = Entities.Field_Tab.Where(i => i.Guid == request.Guid).FirstOrDefault();
                        if (FieldTab == null)
                        {
                            rm.Succeed = false;
                            rm.Message = "无现场服务信息";
                        }
                        rm.Message = FieldTab.Guid;
                        FieldTab.RepairId = request.RepairId;
                        FieldTab.Describe = request.Describe;
                        FieldTab.RepairOrChange = request.RepairOrChange;
                        FieldTab.State = request.State;
                        FieldTab.AddTime = System.DateTime.Now;

                        Entities.Field_Tab.Add(FieldTab);
                        Entities.Entry<Field_Tab>(FieldTab).State = System.Data.Entity.EntityState.Modified;

                        //if (!string.IsNullOrEmpty(request.ImagePaths))
                        //{
                        //    string[] ImagePaths = request.ImagePaths.Split(',');
                        //    foreach (string ImagePath in ImagePaths)
                        //    {
                        //        Image_Tab it = new Image_Tab();
                        //        it.FGuid = FieldTab.Guid;
                        //        it.AddTime = System.DateTime.Now;
                        //        it.ImagePath = ImagePath;
                        //        it.ModuleID = 0;
                        //        Entities.Image_Tab.Add(it);
                        //        Entities.Entry<Image_Tab>(it).State = System.Data.Entity.EntityState.Added;
                        //    }
                        //}
                        if (request.List != null && request.List.Count > 0)
                        {

                            foreach (FieldImage ImagePath in request.List)
                            {
                                Image_Tab it = new Image_Tab();
                                it.Guid = Guid.NewGuid().ToString();
                                it.FGuid = FieldTab.Guid; ;
                                it.AddTime = ImagePath.AddTime;
                                it.ImagePath = ImagePath.url;
                                it.ModuleID = ImagePath.ModuleID;
                                Entities.Image_Tab.Add(it);
                                Entities.Entry<Image_Tab>(it).State = System.Data.Entity.EntityState.Added;
                            }
                        }


                        //查询上一步操作 更新其状态为已完成

                        RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step-1) && i.State == 0).FirstOrDefault();
                        if (stepRepairRelation != null && request.State != 0)
                        {
                            stepRepairRelation.State = 1;
                            Entities.RepairRelation_Tab.Add(stepRepairRelation);
                            Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                        }

                        //报修关系表
                        RepairRelation_Tab RepairRelationTab = Entities.RepairRelation_Tab.Where(i => i.RelationGuid == request.Guid).FirstOrDefault();

                        RepairRelationTab.AddTime = System.DateTime.Now;
                        RepairRelationTab.OperatorID = request.OperatorID;
                        RepairRelationTab.Step = request.Step;
                        //结束流程
                        if (request.State == -1)
                        {
                            RepairRelationTab.State = 1;
                            RepairRelationTab.Operator = -1;
                            //报修结束表
                            RepairEnd_Tab ret = new RepairEnd_Tab();
                            ret.Guid = Guid.NewGuid().ToString();
                            ret.RepairId = request.RepairId;
                            ret.EndTime = System.DateTime.Now;
                            Entities.RepairEnd_Tab.Add(ret);
                            Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;
                        }
                        else
                        {
                            RepairRelationTab.State = request.State == 1 ? 0 : 2;
                            RepairRelationTab.Operator = 4;
                        }

                        Entities.RepairRelation_Tab.Add(RepairRelationTab);
                        Entities.Entry<RepairRelation_Tab>(RepairRelationTab).State = System.Data.Entity.EntityState.Modified;


                        //提交保存
                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();

                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }
            }


            return rm;
        }
    }
}
